using System.Threading;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;

namespace WeChat.Controls;

[PseudoClasses(ScrollChanged)]
public sealed class ChatScrollViewer : ScrollViewer
{
    private const string ScrollChanged = ":scrollChanged";

    private readonly Timer _timer;

    public ChatScrollViewer() : base()
    {
        _timer = new Timer(OnRemoveScrollChangedCallback, null, Timeout.Infinite,
            Timeout.Infinite);
    }

    /// <summary>
    /// 自动隐藏滚动条间隔时间默认3秒
    /// </summary>
    public static readonly StyledProperty<int> AutoHideScrollIntervalProperty = AvaloniaProperty
        .Register<ChatScrollViewer,
            int>(
            nameof(AutoHideScrollInterval), 1000);

    public int AutoHideScrollInterval
    {
        get => GetValue(AutoHideScrollIntervalProperty);
        set => SetValue(AutoHideScrollIntervalProperty, value);
    }

    private void OnRemoveScrollChangedCallback(object? state)
    {
        try
        {
            Avalonia.Threading.Dispatcher.UIThread.Invoke(() =>  PseudoClasses.Set(ScrollChanged, false));
        }
        finally
        {
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
        }
    }

    protected override void OnScrollChanged(ScrollChangedEventArgs e)
    {
        base.OnScrollChanged(e);

        PseudoClasses.Set(ScrollChanged, true);

        //每次滚动都重置定时器让其不会清理 ScrollChanged 伪类
        _timer.Change(AutoHideScrollInterval, AutoHideScrollInterval);
    }
}